package otamanagelogic

import (
	"context"
	"gitee.com/unitedrhino/share/ctxs"
	"gitee.com/unitedrhino/share/errors"
	"gitee.com/unitedrhino/things/service/dmsvr/internal/repo/relationDB"
	"gitee.com/unitedrhino/things/share/domain/deviceMsg/msgOta"

	"gitee.com/unitedrhino/things/service/dmsvr/internal/svc"
	"gitee.com/unitedrhino/things/service/dmsvr/pb/dm"

	"github.com/zeromicro/go-zero/core/logx"
)

type OtaFirmwareDeviceCancelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOtaFirmwareDeviceCancelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OtaFirmwareDeviceCancelLogic {
	return &OtaFirmwareDeviceCancelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 取消指定批次下的设备升级作业
func (l *OtaFirmwareDeviceCancelLogic) OtaFirmwareDeviceCancel(in *dm.OtaFirmwareDeviceCancelReq) (*dm.Empty, error) {
	if err := ctxs.IsRoot(l.ctx); err != nil {
		return nil, err
	}
	l.ctx = ctxs.WithRoot(l.ctx)
	if len(in.DeviceNames) == 0 {
		return nil, errors.Parameter.AddMsg("设备名列表必填")
	}
	err := relationDB.NewOtaFirmwareDeviceRepo(l.ctx).BatchUpdateField(l.ctx, relationDB.OtaFirmwareDeviceFilter{
		FirmwareID:  in.FirmwareID,
		JobID:       in.JobID,
		DeviceNames: in.DeviceNames,
		Statues:     []int64{msgOta.DeviceStatusConfirm, msgOta.DeviceStatusQueued},
	}, map[string]interface{}{"status": msgOta.DeviceStatusCanceled})
	return &dm.Empty{}, err
}
